package sword_offer;

/**
 * @author Synhard
 * @version 1.0
 * @Class sword_offer.Code18
 * @Description 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 * 返回删除后的链表的头节点。
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-14 20:55
 */
public class Code18 {
    public static ListNode deleteNode(ListNode head, int val) {
        if (head.val == val && head.next == null) {
            return null;
        }
        if (head.val == val) {
            return head.next;
        }
        ListNode pre = head;
        ListNode p = head.next;
        while (p != null) {
            if (p.val == val) {
                pre.next = p.next;
                p = pre.next;
                pre = pre.next;
            } else {
                p = p.next;
                pre = pre.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        head.next = new ListNode(5);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(9);
        ListNode p = deleteNode(head, 5);
        while (p != null) {
            System.out.println(p.val);
            p = p.next;
        }
    }
}
